<template>
  <el-dialog :title="title" :visible="visible" append-to-body @close="close">
    <el-form
      ref="form"
      :model="entityData"
      :rules="rules"
      label-width="80px"
      label-position="right"
      style="width:90%;margin:0px auto;"
    >
      <!--表单区域 -->
      <el-form-item label="名称" prop="name">
        <el-input v-model="entityData.name" :readonly="readonly" />
      </el-form-item>

      <el-form-item label="内容" prop="content" class="conditonContent">
        <div
          v-for="(group, groupIndex) in searchConditions"
          :key="groupIndex"
          class="group-container"
        >
          <div class="button-group">
            <el-switch
              v-if="groupIndex > 0"
              v-model="group.operator"
              active-color="#409eff"
              inactive-color="#67c23a"
              :active-text="groupOperators[0].label"
              :inactive-text="groupOperators[1].label"
              :active-value="groupOperators[0].value"
              :inactive-value="groupOperators[1].value"
            />
            <el-button-group style="float:right;">
              <el-button
                type="primary"
                icon="el-icon-plus"
                class="button"
                @click="addRow(group.id)"
              >添加行</el-button>
              <el-button
                type="primary"
                icon="el-icon-plus"
                class="button"
                @click="addGroup(group.id)"
              >添加组</el-button>
              <el-button
                type="primary"
                icon="el-icon-delete"
                class="button"
                @click="deleteGroup(group.id)"
              >删除组</el-button>
            </el-button-group>
          </div>
          <div v-for="(row, r) in group.condition" :key="r" class="row">
            <!-- 字段 下拉列表 -->
            <div style="width:150px;">
              <el-select v-model="row.code" @change="fieldChange(row)">
                <el-option
                  v-for="(field, index) in fieldList"
                  :key="index"
                  :label="field.name"
                  :value="field.code"
                />
              </el-select>
            </div>
            <!-- 操作类型 下拉列表 -->
            <div else style="width:150px;">
              <el-select v-model="row.operator">
                <el-option
                  v-for="(operator,index) in getOperatorByDataType(getFieldByCode(row.code).dataType)"
                  :key="index"
                  :label="operator.label"
                  :value="operator.value"
                />
              </el-select>
            </div>
            <!-- 值 根据操作类型不同，展示不同，例如单个文本框、起止范围、弹出选择窗口等 -->
            <div style="flex:1">
              <!-- 只有当操作符不是null和notnull时，才需要加载值控件 -->
              <div
                v-if="row.operator !== 'NL' && row.operator !== 'NN'"
                style="height:100%;width:100%;"
              >
                <!-- 文本 -->
                <div v-if="getFieldByCode(row.code).dataType === 'text'" class="row-value">
                  <div style="flex:1">
                    <el-input v-model="row.value" />
                  </div>
                </div>
                <!-- 日期 -->
                <div v-else-if="getFieldByCode(row.code).dataType === 'date'" class="row-value">
                  <div style="flex:1">
                    <el-date-picker v-model="row.value" :type="date" style="width:100%" />
                  </div>
                </div>
                <!-- 时间 -->
                <div v-else-if="getFieldByCode(row.code).dataType === 'datatime'" class="row-value">
                  <div style="flex:1;">
                    <el-date-picker v-model="row.value" :type="datatime" style="width:100%" />
                  </div>
                </div>
                <!-- 数值 -->
                <div v-else-if="getFieldByCode(row.code).dataType === 'decimal'" class="row-value">
                  <div style="flex:1">
                    <el-input v-model="row.value" />
                  </div>
                </div>
                <!-- 数据字典 -->
                <div
                  v-else-if="getFieldByCode(row.code).dataType === 'dataDictionary'"
                  class="row-value"
                >
                  <div style="flex:1">
                    <dictionary-select
                      v-model="row.value"
                      multiple
                      :code="getFieldByCode(row.code).dataCode"
                    />
                  </div>
                </div>
                <!-- 用户 单选 -->
                <div
                  v-else-if="getFieldByCode(row.code).dataType === 'singleUser'"
                  class="row-value"
                >
                  <div style="flex:1">
                    <user-single-select v-model="row.value" />
                  </div>
                </div>
                <!-- 用户 多选 -->
                <div
                  v-else-if="getFieldByCode(row.code).dataType === 'multipleUser'"
                  class="row-value"
                >
                  <div style="flex:1">
                    <user-multiple-select v-model="row.value" />
                  </div>
                </div>
                <!-- 组织机构 单选 -->
                <div
                  v-else-if="getFieldByCode(row.code).dataType === 'singleOrganization'"
                  class="row-value"
                >
                  <div style="flex:1">
                    <organization-single-select v-model="row.value" :ref-object="row" />
                  </div>
                </div>
                <!-- 组织机构 多选  -->
                <div
                  v-else-if="getFieldByCode(row.code).dataType === 'multipleOrganization'"
                  class="row-value"
                >
                  <div style="flex:1">
                    <organization-multiple-select v-model="row.value" :ref-object="row" />
                  </div>
                </div>
              </div>
            </div>
            <div class="row-delete">
              <i
                class="el-icon-delete"
                style="font-size:20px;cursor:pointer;"
                @click="deleteRow(group.id, row.id)"
              />
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="排序号" prop="orderNo">
        <el-input v-model="entityData.orderNo" :readonly="readonly" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="doAdvanceQuery">查询</el-button>
      <el-button v-show="saveButtonVisible" type="primary" @click="save">保存</el-button>
      <el-button @click="close">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { detailMixin } from '@/mixin/detailMixin'
const MODULE_CODE = 'support'
const ENTITY_TYPE = 'advanceQueryScheme'
export default {
  name: ENTITY_TYPE + '-detail',
  mixins: [detailMixin],
  props: {
    // 高级查询方案编码
    entityCode: {
      type: String,
      default: ''
    },
    // 字段列表
    fieldList: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      entityType: ENTITY_TYPE,
      moduleCode: MODULE_CODE,
      // eslint-disable-next-line no-eval
      api: eval('this.$api.' + MODULE_CODE + '.' + ENTITY_TYPE),
      pageCode: MODULE_CODE + ':' + ENTITY_TYPE + ':',
      entityData: {

      },
      rules: {
        // 前端验证规则
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ]
      },
      // 分组操作符
      groupOperators: [{
        value: 'AND',
        label: '且'
      },
      {
        value: 'OR',
        label: '或'
      }],
      // 查询条件
      searchConditions: []
    }
  },
  methods: {
    // 复制新增
    clone(entity) {
      this.entityData = entity
      this.entityData.id = null
      this.searchConditions = JSON.parse(this.entityData.content)
      this.mode = 'add'
      this.visible = true
    },

    afterAdd() {
      // 如首次进入，查询条件为空，则默认创建一个组和一个行
      this.searchConditions = []
      const group = {
        id: this.generateId(),
        operator: 'AND',
        condition: [this.createRow()]
      }
      this.searchConditions.push(group)
    },
    afterModify() {
      this.searchConditions = JSON.parse(this.entityData.content)
    },
    beforeSave() {
      this.entityData.entityCode = this.entityCode
      this.entityData.content = JSON.stringify(this.searchConditions)
    },
    doAdvanceQuery() {
      this.$emit('doQuery', JSON.stringify(this.searchConditions))
      this.close()
    },

    // 生成组或者行记录唯一标识
    generateId() {
      return +new Date() + ((Math.random() * 1000).toFixed(0) + '')
    },
    // 根据编码获得其字段对象
    getFieldByCode(code) {
      return this.fieldList.find(item => item.code === code)
    },
    // 根据数据类型获取操作符列表
    getOperatorByDataType(dataType) {
      // 初始化为公用操作，适合所有数据类型
      let operatorList = [{
        value: 'EQ',
        label: '等于'
      },
      {
        value: 'NE',
        label: '不等于'
      },
      {
        value: 'NL',
        label: '为空'
      },
      {
        value: 'NN',
        label: '不为空'
      }]

      if (dataType === 'text') {
        // 文本类型，附加包含操作
        operatorList.push(
          {
            value: 'LK',
            label: '包含'
          },
          {
            value: 'RL',
            label: '以……起始'
          },
          {
            value: 'LL',
            label: '以……结束'
          })
      } else if (dataType === 'date' || dataType === 'datetime' || dataType === 'decimal') {
        // 日期、时间、数值类型，附加比较类型操作
        operatorList.push(
          {
            value: 'LT',
            label: '小于'
          },
          {
            value: 'LQ',
            label: '小于等于'
          },
          {
            value: 'GT',
            label: '大于'
          },
          {
            value: 'GE',
            label: '大于等于'
          }
        )
      } else if (dataType === 'dataDictionary' || dataType === 'multipleUser' || dataType === 'multipleOrganization') {
        // 数据字典、人员多选、组织机构多选
        operatorList = [{
          value: 'IN',
          label: '包含'
        }]
      }
      return operatorList
    },

    // // 查询(将查询条件对象传递给父窗口)
    // query() {
    //   this.$emit('search-action', this.searchConditions)
    //   this.close()
    // },

    // 变更查询字段
    fieldChange(row) {
      row.operator = ''
      row.value = ''
    },

    // 创建行对象
    createRow() {
      return {
        id: this.generateId(),
        code: this.fieldList[0].code,
        operator: '',
        value: ''
      }
    },
    // 新增行
    addRow(id) {
      const group = this.searchConditions.find(group => group.id === id)
      if (group) {
        group.condition.push(this.createRow())
      }
    },
    // 删除行
    deleteRow(id, rid) {
      const group = this.searchConditions.find(group => group.id === id)
      if (group) {
        if (group.condition && group.condition.length === 1) {
          this.$message.error('分组下至少存在一个查询条件')
          return
        }
        const index = group.condition.findIndex(r => r.id === rid)
        group.condition.splice(index, 1)
      }
    },

    // 新增组
    addGroup(id) {
      const groupIndex = this.searchConditions.findIndex(group => group.id === id)

      const group = {
        id: this.generateId(),
        operator: this.groupOperators[0].value,
        condition: [this.createRow()]
      }
      this.searchConditions.splice(groupIndex + 1, 0, group)
    },
    // 删除组
    deleteGroup(id) {
      if (this.searchConditions && this.searchConditions.length === 1) {
        this.$message.error('至少存在一个分组')
        return
      }
      const index = this.searchConditions.findIndex(group => group.id === id)
      this.searchConditions.splice(index, 1)
    }

  }

}
</script>

<style lang="scss" scoped>
.conditonContent {
  .group-container {
    margin-top: 25px;
    .button-group {
      height: 30px;
      padding-top: 0px;
      .button {
        height: 30px;
        padding: 0px 5px;
      }
    }
    .row {
      display: flex;
      margin-top: 5px;
      .row-value {
        height: 100%;
        display: flex;
        align-items: center;
        .between-label {
          width: 30px;
          text-align: center;
          font-weight: bold;
        }
      }
      .row-delete {
        width: 50px;
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }
    }
  }
}
</style>
